<template>
  <view class="forecast-settings">
    <view class="settings-grid">
      <!-- 预报开始时间 -->
      <view class="setting-item">
        <text class="setting-label">预报开始时间</text>
        <input 
          class="setting-input"
          type="datetime-local" 
          v-model="localSettings.startTime"
          @change="handleChange"
          @input="handleChange"
        />
        <text class="setting-hint">默认当天早上8:00</text>
      </view>

      <!-- 预热期长度 -->
      <view class="setting-item">
        <text class="setting-label">预热期长度（天）</text>
        <view class="number-input-wrapper">
          <button class="number-btn" @click="adjustWarmup(-1)">-</button>
          <input 
            class="setting-input number-input"
            type="number" 
            v-model.number="localSettings.prdt"
            @change="handleChange"
            min="1"
            max="90"
          />
          <button class="number-btn" @click="adjustWarmup(1)">+</button>
        </view>
        <text class="setting-hint">建议15-45天，默认30天</text>
      </view>

      <!-- 预见期长度 -->
      <view class="setting-item">
        <text class="setting-label">预见期长度（天）</text>
        <view class="number-input-wrapper">
          <button class="number-btn" @click="adjustForecast(-1)">-</button>
          <input 
            class="setting-input number-input"
            type="number" 
            v-model.number="localSettings.clen"
            @change="handleChange"
            min="1"
            max="15"
          />
          <button class="number-btn" @click="adjustForecast(1)">+</button>
        </view>
        <text class="setting-hint">建议1-7天，默认3天</text>
      </view>

      <!-- 降雨预见期长度 -->
      <view class="setting-item">
        <text class="setting-label">降雨预见期长度（天）</text>
        <view class="number-input-wrapper">
          <button class="number-btn" @click="adjustRainfallForecast(-1)">-</button>
          <input 
            class="setting-input number-input"
            type="number" 
            v-model.number="localSettings.rainfall_clen"
            @change="handleChange"
            min="1"
            max="15"
          />
          <button class="number-btn" @click="adjustRainfallForecast(1)">+</button>
        </view>
        <text class="setting-hint">降雨数据的预见期，默认等于预见期</text>
      </view>

      <!-- 时段划分 -->
      <view class="setting-item setting-item-full">
        <text class="setting-label">时段划分</text>
        <view class="radio-group-inline">
          <view 
            v-for="option in timeStepOptions" 
            :key="option.value"
            class="radio-item-inline"
            :class="{ active: localSettings.timeStep === option.value }"
            @click="selectTimeStep(option.value)"
          >
            <text class="radio-label">{{ option.label }}</text>
          </view>
        </view>
        <text class="setting-hint">{{ currentTimeStepDesc }}</text>
      </view>
    </view>

    <!-- 配置摘要 -->
    <view class="settings-summary">
      <text class="summary-title">配置摘要</text>
      <view class="summary-content">
        <text class="summary-item">
          开始时间: {{ formatDateTime(localSettings.startTime) }}
        </text>
        <text class="summary-item">
          预热期: {{ localSettings.prdt }}天 ({{ formatDateRange('warmup') }})，{{ warmupTimeSteps }}个时段
        </text>
        <text class="summary-item">
          预见期: {{ localSettings.clen }}天 ({{ formatDateRange('forecast') }})，{{ forecastTimeSteps }}个时段
        </text>
        <text class="summary-item">
          降雨预见期: {{ localSettings.rainfall_clen }}天，{{ rainfallForecastTimeSteps }}个时段
        </text>
      </view>
    </view>
  </view>
</template>

<script>
import { ref, computed, watch } from 'vue'

export default {
  name: 'ForecastSettings',
  props: {
    settings: {
      type: Object,
      default: () => ({
        startTime: '',
        prdt: 30,         // 预热期
        clen: 3,          // 预见期
        rainfall_clen: 3, // 降雨预见期
        timeStep: 8       // 每天8个时段
      })
    }
  },
  emits: ['update:settings', 'settings-change'],
  setup(props, { emit }) {
    const localSettings = ref({ ...props.settings })
    
    // 监听 props 变化，同步到 localSettings
    watch(() => props.settings, (newSettings) => {
      if (newSettings) {
        localSettings.value = { ...newSettings }
      }
    }, { deep: true })

    const timeStepOptions = [
      { value: 8, label: '8时段/天', desc: '每3小时一个时段' },
      { value: 24, label: '24时段/天', desc: '每小时一个时段' },
      { value: 1, label: '1时段/天', desc: '日均值' }
    ]

    const warmupTimeSteps = computed(() => {
      return localSettings.value.prdt * localSettings.value.timeStep
    })

    const forecastTimeSteps = computed(() => {
      return localSettings.value.clen * localSettings.value.timeStep
    })

    const rainfallForecastTimeSteps = computed(() => {
      return localSettings.value.rainfall_clen * localSettings.value.timeStep
    })

    const currentTimeStepDesc = computed(() => {
      const option = timeStepOptions.find(opt => opt.value === localSettings.value.timeStep)
      return option ? option.desc : ''
    })

    const adjustWarmup = (delta) => {
      const newValue = localSettings.value.prdt + delta
      if (newValue >= 1 && newValue <= 90) {
        localSettings.value.prdt = newValue
        handleChange()
      }
    }

    const adjustForecast = (delta) => {
      const newValue = localSettings.value.clen + delta
      if (newValue >= 1 && newValue <= 15) {
        localSettings.value.clen = newValue
        // 同时更新降雨预见期（如果相等的话）
        if (localSettings.value.rainfall_clen === localSettings.value.clen - delta) {
          localSettings.value.rainfall_clen = newValue
        }
        handleChange()
      }
    }

    const adjustRainfallForecast = (delta) => {
      const newValue = localSettings.value.rainfall_clen + delta
      if (newValue >= 1 && newValue <= 15) {
        localSettings.value.rainfall_clen = newValue
        handleChange()
      }
    }

    const selectTimeStep = (value) => {
      localSettings.value.timeStep = value
      handleChange()
    }

    const handleChange = () => {
      console.log('ForecastSettings handleChange 被调用, localSettings:', localSettings.value)
      emit('update:settings', { ...localSettings.value })
      emit('settings-change', { ...localSettings.value })
    }

    const formatDateTime = (dateTimeStr) => {
      if (!dateTimeStr) return '-'
      const date = new Date(dateTimeStr)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    const formatDateRange = (type) => {
      if (!localSettings.value.startTime) return '-'
      
      const start = new Date(localSettings.value.startTime)
      const days = type === 'warmup' 
        ? -localSettings.value.prdt 
        : localSettings.value.clen
      
      const end = new Date(start)
      end.setDate(end.getDate() + days)
      
      const formatDate = (date) => {
        return date.toLocaleDateString('zh-CN', {
          month: '2-digit',
          day: '2-digit'
        })
      }
      
      if (type === 'warmup') {
        return `${formatDate(end)} - ${formatDate(start)}`
      } else {
        return `${formatDate(start)} - ${formatDate(end)}`
      }
    }

    watch(() => props.settings, (newSettings) => {
      localSettings.value = { ...newSettings }
    }, { deep: true })

    return {
      localSettings,
      timeStepOptions,
      warmupTimeSteps,
      forecastTimeSteps,
      rainfallForecastTimeSteps,
      currentTimeStepDesc,
      adjustWarmup,
      adjustForecast,
      adjustRainfallForecast,
      selectTimeStep,
      handleChange,
      formatDateTime,
      formatDateRange
    }
  }
}
</script>

<style scoped>
.forecast-settings {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.settings-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

.setting-item {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.setting-label {
  font-size: 14px;
  color: #303133;
  font-weight: 600;
  line-height: 1.6;
}

.setting-input {
  padding: 12px 14px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
  background-color: #fff;
  transition: all 0.3s;
  min-height: 42px;
  line-height: 1.5;
  box-sizing: border-box;
}

.setting-input:focus {
  border-color: #409eff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.setting-hint {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
}

.number-input-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}

.number-btn {
  width: 42px;
  height: 42px;
  padding: 0;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  color: #606266;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.number-btn:hover {
  border-color: #409eff;
  color: #409eff;
  background-color: #ecf5ff;
}

.number-btn:active {
  transform: scale(0.95);
}

.number-input {
  flex: 1;
  text-align: center;
  font-weight: 600;
  font-size: 16px;
  color: #409eff;
}

/* 时段划分横向布局 */
.setting-item-full {
  grid-column: 1 / -1;
}

.radio-group-inline {
  display: flex;
  gap: 12px;
}

.radio-item-inline {
  flex: 1;
  padding: 12px 20px;
  border: 2px solid #e4e7ed;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  text-align: center;
}

.radio-item-inline:hover {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.radio-item-inline.active {
  border-color: #409eff;
  background-color: #ecf5ff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.radio-item-inline .radio-label {
  font-size: 14px;
  color: #303133;
  font-weight: 600;
}

.settings-summary {
  padding: 16px;
  background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
  border-left: 3px solid #409eff;
  border-radius: 6px;
}

.summary-title {
  font-size: 14px;
  color: #303133;
  font-weight: 600;
  margin-bottom: 12px;
  display: block;
}

.summary-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.summary-item {
  font-size: 13px;
  color: #606266;
  line-height: 1.6;
}
</style>

